package com.zb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.ZjSpareCustomParam;
import com.zb.mapper.ZjSpareCustomParamMapper;
import com.zb.service.ZjSpareCustomParamService;
import com.zb.vo.GoodsCustomParamVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 备件自定义参数关联表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-08-15
 */
@Service
public class ZjSpareCustomParamServiceImpl extends ServiceImpl<ZjSpareCustomParamMapper, ZjSpareCustomParam> implements ZjSpareCustomParamService {

    // 新增、修改、删除备件自定义参数
    @Override
    public void save(Long custAccId, Long spareId, List<GoodsCustomParamVo> customParamVos, List<Long> delCustomParamIds) {
        if (null != delCustomParamIds && !delCustomParamIds.isEmpty()) {
            this.removeByIds(delCustomParamIds);
        }
        if (null == customParamVos || customParamVos.isEmpty()) {
            return;
        }
        List<ZjSpareCustomParam> adds = new ArrayList<>();
        List<ZjSpareCustomParam> updates = new ArrayList<>();
        ZjSpareCustomParam param = null;
        for (GoodsCustomParamVo vo : customParamVos) {
            param = new ZjSpareCustomParam();
            BeanUtils.copyProperties(vo, param);
            if (null != param.getId()) {
                updates.add(param);
                continue;
            }
            param.setId(IdWorker.getId());
            param.setCustAccId(custAccId);
            param.setSpareId(spareId);
            adds.add(param);
        }
        if (!adds.isEmpty()) this.saveBatch(adds);
        if (!updates.isEmpty()) this.updateBatchById(updates);
    }

    // 根据备件ID获取自定义参数
    @Override
    public List<ZjSpareCustomParam> getBySpareId(Long spareId) {
        QueryWrapper<ZjSpareCustomParam> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name", "val");
        wrapper.eq("spare_id", spareId);
        return this.list(wrapper);
    }

    // 根据备件ID删除自定义参数
    @Override
    public void deleteBatchBySpareIds(List<Long> spareIds) {
        if (null == spareIds || spareIds.isEmpty()) {
            return;
        }
        QueryWrapper<ZjSpareCustomParam> wrapper = new QueryWrapper<>();
        wrapper.in("spare_id", spareIds);
        this.remove(wrapper);
    }
}
